package com.lizhi.note.controller;

import com.lizhi.note.dto.NotepageDTO;
import com.lizhi.note.payload.ApiResponse;
import com.lizhi.note.payload.ResponseUtil;
import com.lizhi.note.service.NotepageService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/notepages")
public class NotepageController {

    private final NotepageService notepageService;

    public NotepageController(NotepageService notepageService) {
        this.notepageService = notepageService;
    }

    @PostMapping
    public ResponseEntity<ApiResponse> createNotepage(@Valid @RequestBody NotepageDTO notepageDto) {
        if (notepageDto.getId() == null){
            NotepageDTO createdNotepage = notepageService.createNotepage(notepageDto);
            return ResponseUtil.success(createdNotepage);
        }

        NotepageDTO updatedNotepage = notepageService.updateNotepage(notepageDto);
        return ResponseUtil.success(updatedNotepage);
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse> getNotepage(@PathVariable Long id) {
        Optional<NotepageDTO> notepageDto = notepageService.getNotepageById(id);
        return notepageDto.map(dto -> ResponseUtil.success(dto))
                .orElseGet(() -> ResponseUtil.error(HttpStatus.NOT_FOUND.value(), "id对应笔记没找到"));
    }

    @GetMapping
    public ResponseEntity<ApiResponse> getAllNotepages() {
        List<NotepageDTO> notepages = notepageService.getAllNotepages();
        return ResponseUtil.success(notepages);
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse> updateNotepage(@PathVariable Long id, @Valid @RequestBody NotepageDTO notepageDto) {
        if (!id.equals(notepageDto.getId())) {
            return ResponseUtil.error(HttpStatus.BAD_REQUEST.value(), "bad request,id不匹配");
        }

        NotepageDTO updatedNotepage = notepageService.updateNotepage(notepageDto);
        return ResponseUtil.success(updatedNotepage);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse> deleteNotepage(@PathVariable Long id) {
        notepageService.deleteNotepage(id);
        return ResponseUtil.success(null,"执行成功");
    }

}
